package com.hboxs.asl.qcloudLVB.util;

import com.hboxs.asl.qcloudLVB.Conf;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import static com.tencent.common.MD5.byteArrayToHexString;

/**
 * Created by xxx on 2016/10/12.
 */
public class SafeUrlUtils {


    /**
     * KEY+ stream_id(livecode) + txTime
     *
     * @param key      防盗链key(push,play,api不同)
     * @param streamId 直播码(传入livecode)
     * @param txTime   过期时间
     * @return 防盗链
     */
    public static String getSafeUrl(String key, String streamId, Long txTime) {

        String txSecret = null;

        if (key != null && txTime != null) {

            String input = new StringBuilder().
                    append(key).
                    append(streamId).
                    append(Long.toHexString(txTime).toUpperCase()).toString();

            try {
                MessageDigest messageDigest = MessageDigest.getInstance("MD5");
                txSecret = byteArrayToHexString(
                        messageDigest.digest(input.getBytes("UTF-8")));
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        }

        return txSecret == null ? "" :
                new StringBuilder().
                        append("&txSecret=").
                        append(txSecret).
                        append("&").
                        append("txTime=").
                        append(Long.toHexString(txTime).toUpperCase()).
                        toString();

    }

    /**
     * api-sign获取
     *
     * @param t 过期时间
     * @return josn
     */
    public static String getSign(Long t) {
        String sign = null;

        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            sign = byteArrayToHexString(
                    messageDigest.digest((Conf.API_CALL_KEY + t.toString()).getBytes("UTF-8")));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return sign;
    }

}